package com.zongtui.fourinone.base.config.xml;

import com.zongtui.fourinone.obj.ObjValue;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;

/**
 * 获取xml对象.
 */
public class XmlObjectCallback extends DefaultHandler {
    private boolean textFlag = false;
    private ArrayList objList;
    private ObjValue currentObj;
    private String curKey;
    private String propsRowDesc;
    private String keyDesc;
    private String curPropsRowDesc;
    private String curKeyDesc;

    public XmlObjectCallback() {
    }

    public void startDocument() throws SAXException {
        //LogUtil.fine("start parse xml");
    }

    public void startElement(String uri, String sName, String qName, Attributes attrs) {
        switch (qName) {
            case "propsTable":
                objList = new ArrayList();
                break;
            case "propsRow":
                curPropsRowDesc = attrs.getValue("desc");
                currentObj = new ObjValue();
                break;
            default:
                curKeyDesc = attrs.getValue("desc");
                curKey = qName;
                textFlag = true;
                break;
        }
    }

    public void characters(char[] data, int start, int length) {
        String content = new String(data, start, length);
        if (textFlag) {
            //LogUtil.fine(content);
            if (keyDesc == null || (curKeyDesc != null && curKeyDesc.equals(keyDesc)))
                currentObj.setString(curKey, content.trim());
        }
    }

    public void endElement(String uri, String sName, String qName) {

        switch (qName) {
            case "propsTable":
                break;
            case "propsRow":
                if (propsRowDesc == null || (curPropsRowDesc != null && curPropsRowDesc.equals(propsRowDesc)))
                    objList.add(currentObj);
                break;
            default:
                textFlag = false;
                break;
        }
    }

    public void endDocument() throws SAXException {

    }

    public ArrayList getObjList() {
        return objList;
    }

    public void setPropsRowDesc(String propsRowDesc) {
        this.propsRowDesc = propsRowDesc;
    }

    public void setKeyDesc(String keyDesc) {
        this.keyDesc = keyDesc;
    }
}